<template>
	<div class="uUpload-wrap">
		<div class="pre-box"
			v-if="showUploadList === false && uUploadRef[name] && uUploadRef[name].lists && uUploadRef[name].lists.length">
			<div class="pre-item border-1px" v-for="(item, index) in uUploadRef[name].lists" :key="index">
				<template v-if="item.fileType === 'video'">
					<video class="pre-item-image" :src="item.url" :poster="item.url"
						@tap.stop="doPreviewImage(item, index)"
						:style="{ width: width + 'rpx', height: height + 'rpx' }" />
				</template>
				<template v-else>
					<image class="pre-item-image" :src="computedImgSrc(item.url)"
						@tap.stop="doPreviewImage(item, index)"
						:style="{ width: width + 'rpx', height: height + 'rpx' }" data-id="" +item.fileType+""></image>
				</template>
			</div>
		</div>
		<u-upload :ref="refName" :form-data="formData" :action="action" :max-count="maxCount" :auto-upload="true"
			:show-upload-list="showUploadList" :max-size="maxSize" :width="width" :height="height" :header="header"
			:multiple="multiple" :name="uploadName" :upload-text="uploadText" :custom-btn="customBtn" :show-tips="true"
			:deletable="deleteShow" :showProgress="showProgress" :before-upload="beforeUpload" :file-list="uFileList"
			:fileType="fileType" :limitType="limitType" @on-preview="onPreview" @on-oversize="maxOversize"
			@on-change="onUploadChange" @on-remove="onRemove">
			<template v-slot:addBtn>
				<slot name="addBtn"></slot>
			</template>
		</u-upload>
	</div>
</template>
<script>
	import {
		mapState
	} from 'vuex'

	export default {
		name: 'UploadView',
		props: {
			maxSize: {
				type: Number,
				default: 5 * 1024 * 1024
			}, // 最大尺寸
			url: {
				type: String,
				default: 'aliyun/oss/upload'
			}, // 上传的地址动态路径
			width: {
				type: Number,
				default: 160
			}, // 宽度
			height: {
				type: Number,
				default: 160
			}, // 宽度
			refName: {
				type: String,
				default: 'uUpload'
			}, // ref
			moduleName: {
				type: String,
				default: 'uUpload'
			}, // 模块唯一名称，用于区分多处调用
			uploadName: {
				type: String,
				default: 'file'
			}, // 上传文件的字段名，供后端获取使用
			uploadText: {
				type: String,
				default: '添加图片'
			}, // 文本
			maxCount: {
				type: [String, Number],
				default: 5
			}, // 最多图数
			formData: {
				type: Object,
				default: () => ({})
			},
			customBtn: {
				type: Boolean,
				default: false
			}, // 自定义按钮
			multiple: {
				type: Boolean,
				default: false
			}, // 批量上传
			deleteShow: {
				type: Boolean,
				default: false
			}, // 是否显示删除按钮
			showProgress: {
				type: Boolean,
				default: false
			}, // 是否显示进度条
			showUploadList: {
				type: Boolean,
				default: true
			}, // 组件内部显示预览
			fileList: {
				type: Array,
				default: () => []
			}, // 上传的文件列表,用于默认显示
			fileType: {
				type: String,
				default: () => 'all'
			}, // 上传类型，只支持img|video|all
			limitType: {
				type: Array,
				default: () => ['png', 'jpg', 'jpeg', 'webp', 'gif', 'image']
			}, // 允许上传的图片后缀
			valueName: {
				type: String,
				default: 'bannerList'
			}, // value对应的名字
		},
		data() {
			return {
				action: 'http://124.248.64.74:8085/' + this.url, // 服务器地址
				header: {}, // 请求头
				uUploadRef: {}, // 组件实例
				uFileList: [],
				suffix: this.fileType === 'video' ? '?vframe/jpg/offset/1' : '',
			}
		},
		created() {
			if (!this.uUploadRef[this.refName]) {
				this.$set(this.uUploadRef, this.refName, {})
			}
			this.$set(this.header, 'Authorization', 'Bearer ' + uni.getStorageSync('token'))
			console.log('update created', Date.now(), ';action=', this.action, ';', this.header)
		},
		computed: {
			...mapState('user', {
				token: 'token',
			}),
			// 方法二
			// token: {
			//   get() {
			//     console.log(" token=", this.$store.getters['user/token'], Date.now())
			//     return this.$store.getters['user/token']
			//   },
			// },
		},
		watch: {
			fileList: {
				handler(val) {
					if (val) {
						console.log('watch fileList 预览图片', val, Date.now())
						this.$nextTick(() => {
							const urlList = val.map((item) => {
								return {
									url: item.url,
									progress: 100
								}
								// return { url: this.computedImgSrc(item.url, this.fileType === 'video' ? 'video' : ''), progress: 100 }
							})
							this.$refs[this.refName].lists = urlList // 预览图片
							this.uFileList = urlList
						})
					}
				},
				deep: true,
				immediate: true,
			},
			token: {
				handler(val) {
					if (val) {
						this.$nextTick(() => {
							// 当token过期后，用户重新登录时动态获取token并设置
							this.$set(this.header, 'Authorization', 'Bearer ' + val)
						})
					}
					console.log('watch token==', val, Date.now())
				},
				deep: true,
				immediate: true,
			},
		},
		onReady(options) {
			console.log(
				'onReady=',
				options,
				';t=',
				Date.now(),
				';this.showUploadList=',
				this.showUploadList,
				';this.refName=',
				this.refName,
				';this.$refs[this.refName]=',
				this.$refs[this.refName]
			)
			// 注意这里不能直接挂载实例，会报错的！！！ 20200810
			// this.uUploadRef[this.name] = this.$refs[this.name]
		},
		onUnload() {
			console.log('上传图片 onUnload', Date.now())
		},
		onShow() {
			console.log('上传图片 onShow created', Date.now())
		},
		methods: {
			/**
			 * @author: yiling (315800015@qq.com)
			 * @description: 计算图片src地址
			 * @param {String} name 图片名
			 * @param {String} type 类型
			 * @return {*}
			 * @Date: 2021-04-15 11:23:33
			 */
			computedImgSrc(name, type) {
				return this.$getPictureSrc(name, type)
			},
			/**
			 * @author: yilingsj（315800015@qq.com）
			 * @description: 上传前触发
			 * @param {type}
			 * @return:
			 * @Date: 2020-07-20 10:42:44
			 */
			beforeUpload(index, list) {
				// console.log('内 beforeUpload', index, list, ';t=', Date.now(), ';this=', this, ';this.$refs.door_image=')
				console.log(']===uni', uni)
				// uni.showLoading({
				//   title: '上传中...',
				//   mask: true,
				// })
				// this.$emit('beforeUpload', { index, list, moduleName: this.moduleName }) 此时会报错
			},
			/**
			 * @author: yilingsj（315800015@qq.com）
			 * @description: 最大尺寸
			 * @param {type}
			 * @return {type}
			 * @Date: 2020-08-04 14:25:44
			 */
			maxOversize(file, lists) {
				if (file.size > this.maxSize) {
					uni.hideLoading()
					setTimeout(() => {
						console.log('超过最大尺寸了 ', file, ';lists=', lists, Date.now())
						this.$toast('图片最大为' + (this.maxSize / 1024).toFixed(2) + 'KB')
					}, 0)
					return
				}
				this.$emit('onOversize', {
					file,
					lists,
					moduleName: this.moduleName
				})
			},
			/**
			 * @author: yilingsj（315800015@qq.com）
			 * @description: 上传后触发
			 * @param {type}
			 * @return:
			 * @Date: 2020-07-20 10:43:06
			 */
			onUploadChange(res, index, lists) {
				uni.hideLoading()
				const newFileList = this.$refs[this.refName].lists.filter((item) => item.progress === 100)
				console.log('newFileList=', newFileList, ';lists[index]=', lists[index].progress, Date.now())

				console.log('上传后lists=', lists, ';index=', index, Date.now())
				console.log('onchange 上传后触发', res, ';index', index, ';lists=', lists, ';共花费时间=', Date.now())

				if (res.statusCode === 401) {
					this.$toast('token验证失败，请重新登录')
					this.$refs[this.refName].clear() // 防止重新登录后，上次传的图片显示空白
					setTimeout(() => {
						const routes = getCurrentPages()
						const findIndex = routes.findIndex((item) => item.route.match('/login/login'))
						console.log('findIndex=', findIndex)
						if (findIndex === -1) {
							uni.navigateTo({
								url: '/pages/login/login',
							})
						}
					}, 0)
					return
				}

				const data = lists[index].response
				if (res.statusCode === 200) {
					if (newFileList.length === lists.length) {
						// this.uUploadRef[this.refName] = {
						//   lists: this.$refs[this.refName].lists,
						// }
						const result = this.filterUrl(newFileList)
						// this.$set(parent, this.valueName, result)
						this.$emit('onChange', {
							res,
							index,
							lists,
							moduleName: this.moduleName,
							result
						})
						console.log('成功result', data, ';result=', result)
					}
				}
				console.log('onchange 上传后触发', res, ';index', index, ';lists=', lists, ';共花费时间=', Date.now())
			},
			/**
			 * @author: yiling (315800015@qq.com)
			 * @description: 过滤url
			 * @param {*} list
			 * @return {*}
			 * @Date: 2021-06-18 15:05:15
			 */
			filterUrl(list) {
				const result = list.map((item) => {
					const url = item.response ? item.response.data[0].frontUrl : item.url
					return {
						progress: item.progress,
						url: url,
						// url: '/uploads' + url.split('/uploads')[1], // 过滤双斜线
						// url: url.replace('//uploads', '/uploads'), // 过滤双斜线
					}
				})
				return result
			},
			/**
			 * @author: yiling (315800015@qq.com)
			 * @description: 移除图片时触发
			 * @param {Number} index 索引
			 * @param {Array} lists 完整数据
			 * @param {Number} name 通过props传递的index参数
			 * @return {*}
			 * @Date: 2021-04-18 12:00:12
			 */
			onRemove(index, lists, name) {
				console.log(
					'onRemove',
					index,
					';lists',
					lists,
					';name',
					name,
					';this.$refs[name].lists=',
					this.$refs[this.refName]
				)

				this.$emit('onRemove', {
					index,
					lists: this.filterUrl(lists),
					name,
					moduleName: this.moduleName
				})
			},
			/**
			 * @author: yiling (315800015@qq.com)
			 * @description: 全屏预览图片时触发
			 * @param {String} url 为当前选中的图片地址
			 * @param {Array} lists 目前组件内的所有图片数组，index为通过props传递的index参数
			 * @param {Number} name 为通过props传递的index参数(1.6.1加入)
			 * @return {*}
			 * @Date: 2021-04-17 11:22:08
			 */
			onPreview(url, lists, name) {
				console.log('全屏预览', url, lists, name)
				this.$emit('onPreview', {
					url: url + this.suffix,
					lists,
					name,
					moduleName: this.moduleName
				})
			},
			/**
			 * @author: yilingsj（315800015@qq.com）
			 * @description: 删除
			 * @param {type}
			 * @return {type}
			 * @Date: 2020-08-10 11:04:25
			 */
			deleteItem(name, index) {
				console.log('name=', name, ';index=', index)
				this.$refs[name].remove(index)
				this.uUploadRef[name] = {
					lists: this.$refs[name].lists,
				}
				this.$emit('deleteItem', {
					name,
					index,
					moduleName: this.moduleName
				})
			},
			/**
			 * @author: yilingsj（315800015@qq.com）
			 * @description: 预览
			 * @param {type}
			 * @return {type}
			 * @Date: 2020-08-30 21:34:19
			 */
			doPreviewImage(item, index) {
				console.log('预览', item, ';', index)
				const url = this.computedImgSrc(item.url)
				this.$refs[this.refName].doPreviewImage(url, index)
			},
		},
	}
</script>
<style lang="scss" scoped>
	.uUpload-wrap {
		width: initial;
	}

	.pre-box {
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex-wrap: wrap;
		min-height: 192rpx;
		width: 100%;
	}

	.pre-item {
		width: 280rpx;
		border-radius: 10rpx;
		height: 192rpx;
		overflow: hidden;
		position: relative;
		margin-bottom: 20rpx;
		margin-right: 20rpx;

		&::after {
			border-color: #e9e9e9;
			border-radius: 20rpx;
		}
	}

	.u-progress {
		position: absolute;
		bottom: 10rpx;
		left: 8rpx;
		right: 8rpx;
		z-index: 9;
		width: auto;
	}

	.pre-item-image {
		width: 280rpx;
		height: 192rpx;
	}

	.u-delete-icon {
		position: absolute;
		top: 10rpx;
		right: 10rpx;
		z-index: 10;
		background-color: $u-type-error;
		border-radius: 100rpx;
		width: 44rpx;
		height: 44rpx;
		display: flex;
		align-items: center;
	}
	
</style>
